<?php

namespace app\api\controller\order;

use think\Controller;

class Order extends Controller{
    public function __construct()
    {
        parent::__construct();

        $this->UserModel=model('User.User');
        $this->OrderModel=model('Order.Order');
        $this->CartModel=model('Cart');
        $this->AddressModel=model('User.Address');
        $this->ProductModel=model('Product.Product');
        $this->OrderProductModel=model('Order.Product');
        $this->RecordModel=model('User.Record');
    }

    public function index(){
        if($this->request->isPost()){
            $userid=$this->request->param('userid',0);
            $status=$this->request->param('status',0);

            $user=$this->UserModel->find($userid);
            if(!$user){
                $this->error('用户不存在');
                exit;
            }

            $where=[
                'userid'=>$userid
            ];

            if($status != 0){
                $where['status']=$status;
            }

            $order=$this->OrderModel->where($where)->select();
            if(!$order){
                $this->success('暂无订单数据');
                exit;
            }

            $orderlist=[];
            foreach($order as $item){
                $info=[
                    'id'=>$item['id'],
                    'code'=>$item['code'],
                    'total'=>$item['total'],
                    'createtime'=>$item['createtime'],
                    'status'=>$item['status'],
                    'status_text'=>$item['status_text'],
                ];

                $product=$this->OrderProductModel->with(['info'])->where(['orderid'=>$item['id']])->find();

                if($product && $product['info']['id']){
                    $info['product']=$product['info'];
                }
                $orderlist[]=$info;
            }
            $this->success('返回订单数据',null,$orderlist);
            exit;
        }
    }

    public function add(){
        if($this->request->isPost()){
            $userid=$this->request->param('userid',0);
            $addrid=$this->request->param('addrid',0);
            $cartids=$this->request->param('cartids','');
            $content=$this->request->param('content','');

            $user=$this->UserModel->find($userid);
            if(!$user){
                $this->error('用户不存在');
                exit;
            }

            $where=[
                'id'=>$addrid,
                'userid'=>$userid
            ];

            // 判断收货地址是否存在
            $address=$this->AddressModel->where($where)->find();

            if(!$address){
                $this->error('收货地址不存在，请重新选择');
                exit;
            }

            $where=[
                'cart.id'=>['in',$cartids],
                'userid'=>$userid
            ];

            $cartlist=$this->CartModel->with(['product'])->where($where)->select();
            if(!$cartlist){
                $this->error('下单数据为空，请重新选择商品');
                exit;
            }

            // 判断商品库存是否充足
            foreach($cartlist as $item){
                $nums=$item['nums'];
                $stock=$item['product']['stock'];

                // 让库存减购物车数量
                $pronums=bcsub($stock,$nums);

                if($pronums < 0){
                    $this->error($item['product']['name'].'库存不足，请重新选择');
                    exit;
                }
            }

            // 查询下单数据的总价格
            $where=[
                'id'=>['in',$cartids],
                'userid'=>$userid
            ];
            $total=$this->CartModel->where($where)->sum('total');

            $point=$user['point'];

            // 让用户积分减总价
            $UpdatePoint=bcsub($point,$total);

            if($UpdatePoint < 0){
                $this->error('积分不足，请先充值后操作');
                exit;
            }

            //订单表(INSERT) 订单商品表(INSERT) 商品库存(update) 用户积分(update) 消费记录(insert) 购物车(delete)
            // 开启事务
            $this->OrderModel->startTrans();
            $this->OrderProductModel->startTrans();
            $this->ProductModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();
            $this->CartModel->startTrans();

            // 组装订单表数据
            $OrderData=[
                'userid'=>$userid,
                'addrid'=>$addrid,
                'code'=>build_code('AK'),
                'content'=>$content,
                'status'=>1,
                'total'=>$total,
            ];

            // 订单表
            $OrderStatus=$this->OrderModel->validate('common/Order/Order')->save($OrderData);
            if($OrderStatus === FALSE){
                $this->error($this->OrderModel->getError());
                exit;
            }

            // 组装订单商品的数据
            $OrderProductData=[];
            $ProductData=[];

            foreach($cartlist as $item){
                // 订单商品
                $OrderProductData[]=[
                    'orderid'=>$this->OrderModel->id,
                    'proid'=>$item['proid'],
                    'nums'=>$item['nums'],
                    'price'=>$item['price'],
                    'total'=>$item['total'],
                ];

                // 商品库存减购物车数量
                $stock=bcsub($item['product']['stock'],$item['nums']);

                $ProductData[]=[
                    'id'=>$item['proid'],
                    'stock'=>$stock
                ];
            }

            // 插入订单商品表数据
            $OrderProductStatus=$this->OrderProductModel->validate('common/Order/Product')->saveAll($OrderProductData);

            if($OrderProductStatus === FALSE){
                // 回滚
                $this->OrderModel->rollback();
                $this->error($this->OrderProductModel->getError());
                exit;
            }

            // 商品更新库存
            $ProductStatus=$this->ProductModel->isUpdate(true)->saveAll($ProductData);

            if($ProductStatus === FALSE){
                // 回滚
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->ProductModel->getError());
                exit;
            }

            // 更新用户积分
            $UserData=[
                'id'=>$userid,
                'point'=>$UpdatePoint
            ];

            $UserStatus=$this->UserModel->isUpdate(true)->save($UserData);

            if($UserStatus === FALSE){
                // 回滚
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->UserModel->getError());
                exit;
            }

            // 消费记录
            $RecordData=[
                'point'=>$total,
                'content'=>"订单号：".$OrderData['code']."---消费的积分为:$total",
                'state'=>5,
                'userid'=>$userid
            ];

            $RecordStatus=$this->RecordModel->validate('common/User/Record')->save($RecordData);
            if($RecordStatus === FALSE){
                // 回滚
                $this->UserModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            // 购物车
            $CartStatus=$this->CartModel->destroy($cartids);
            if($CartStatus === FALSE){
                // 回滚
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->CartModel->getError());
                exit;
            }

            if($OrderStatus !== FALSE && $OrderProductStatus !== FALSE && $ProductStatus !== FALSE && $UserStatus !== FALSE && $RecordStatus !== FALSE && $CartStatus !== FALSE){
                // 提交事务
                $this->OrderModel->commit();
                $this->OrderProductModel->commit();
                $this->ProductModel->commit();
                $this->UserModel->commit();
                $this->RecordModel->commit();
                $this->CartModel->commit();
                $this->success('下单成功，等待商家发货', '/user/base/index');
                exit;
            }else{
                // 回滚
                $this->CartModel->rollback();
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->ProductModel->rollback();
                $this->OrderProductModel->rollback();
                $this->OrderModel->rollback();
                $this->error('下单失败，请重新操作');
                exit;
            }
        }
    }

    public function info(){
        if($this->request->isPost()){
            $userid=$this->request->param('userid',0);
            $orderid=$this->request->param('orderid',0);

            $where=[
                'userid'=>$userid,
                'id'=>$orderid
            ];

            $order=$this->OrderModel->where($where)->find();

            if(!$order){
                $this->error('订单不存在');
                exit;
            }

            $product=$this->OrderProductModel->with(['info'])->where(['orderid'=>$orderid])->select();

            if(!$product){
                $this->error('订单商品不存在');
                exit;
            }

            $address=$this->AddressModel->with(['provinces','citys','districts'])->find($order['addrid']);

            if(!$address){
                $this->error('未找到订单的收货地址');
                exit;
            }

            $data=[
                'order'=>$order,
                'product'=>$product,
                'address'=>$address,
            ];

            $this->success('返回订单数据成功',null,$data);
            exit;
        }
    }
}